package com.hxzy.shop.cachedao;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.hxzy.shop.constant.RedisConstant;
import com.hxzy.shop.dto.UserDto;
import com.hxzy.shop.entity.Member;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName AuthCacheServiceImpl
 * @Author wengjt
 * @Date 2021/7/7 17:14
 * @Description
 **/
@Service
public class AuthCacheServiceImpl implements AuthCacheService {

    private static final String APPLET_USER_INFO= RedisConstant.APPLET_USER_INFO;
    private static final String BACK_USER_INFO=RedisConstant.REQUEST_USER_INFO;
    private static final String BACK_CAPTCHA_CODE=RedisConstant.BACK_CAPTCHA_CODE;
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public Member getAppleteUserInfo(String token) {
        if (ObjectUtil.isEmpty(token)){
            return null;
        }
        String memberStr = redisTemplate.opsForValue().get(APPLET_USER_INFO+token);
        redisTemplate.expire(APPLET_USER_INFO+token,7,TimeUnit.DAYS);
        Member member = JSONUtil.toBean(memberStr, Member.class);
        return member;
    }

    @Override
    public UserDto getBackUserInfo(String token) {
        if (ObjectUtil.isEmpty(token)){
            return null;
        }
        String  key=BACK_USER_INFO+token;
        String memberStr = redisTemplate.opsForValue().get(key);
        redisTemplate.expire(key,24,TimeUnit.HOURS);
        UserDto userDto = JSONUtil.toBean(memberStr, UserDto.class);
        return userDto;
    }

    @Override
    public Boolean savaCaptchaCode(String captchaNo, String captchaCode) {
        redisTemplate.opsForValue().set(BACK_CAPTCHA_CODE+captchaNo,captchaCode,3, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public Boolean checkCaptchaCode(String captchaNo, String captchaCode) {
        String code = redisTemplate.opsForValue().get(BACK_CAPTCHA_CODE + captchaNo);
        if (ObjectUtil.isNotEmpty(code)&&code.equalsIgnoreCase(captchaCode)){
            return true;
        }
        return false;
    }

    @Override
    public String getToken(String k) {
        return redisTemplate.opsForValue().get(k);
    }
}
